package com.ta.stage.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //shiroFilterBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultWebSecurityManager);
        /**
         * 设置shiro的内置过滤器
         * anon 无需认证就可以访问
         * authc 必须认证才可以访问
         * user 必须拥有记住我功能才可以用
         * perms 拥有对某个资源的权限才能访问
         */
        //拦截
        Map<String,String> filterMapper = new LinkedHashMap<>();
        //授权:正常情况下没有授权会跳转到授权页面
        filterMapper.put("/user/add","perms[user:add]");

        //filterMapper.put("/user/add","authc");
        filterMapper.put("/user/update","authc");
        //支持通配符
        //filterMapper.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMapper);


        //设置登录请求 不要跳404错误
        bean.setLoginUrl("/zg/toLogin");
        //设置未经授权不能登录
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }
    //DefaultWebSurityManager
    @Bean(name = "defaultSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建Realm对象，自定义
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }

}
